/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.model;

import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.directwebremoting.annotations.DataTransferObject;
import org.directwebremoting.annotations.RemoteProperty;
import org.hibernate.validator.NotEmpty;
import org.internna.iwebjtracker.security.Credentials;
import org.internna.iwebjtracker.server.connection.ConnectionDetails;
import org.internna.iwebjtracker.utils.UrlUtils;
import org.internna.iwebmvc.metadata.EntitySecurity;
import org.internna.iwebmvc.metadata.EntitySecurity.CRUD;
import org.internna.iwebmvc.metadata.EntitySecurityRule;
import org.internna.iwebmvc.metadata.ui.EntityFilter;
import org.internna.iwebmvc.metadata.ui.FormField;
import org.internna.iwebmvc.metadata.ui.GridColumn;
import org.internna.iwebmvc.model.AbstractOwnedDomainEntity;
import org.internna.iwebmvc.utils.CollectionUtils;

/**
 * Default connection details to open a channel with a server. Only the user who
 * created the data can modify it later. Only users with the authority of
 * ROLE_PROJECT_MANAGER assigned can create items of this type.
 *
 * @author Jose Noheda
 * @since 1.0
 */
@Entity
@Table(name = "CONNECTIONS")
@NamedQuery(name = "DefaultConnectionDetails.findAll", query = "SELECT d FROM DefaultConnectionDetails d")
@EntitySecurity({
    @EntitySecurityRule(operation = CRUD.SAVE_OR_UPDATE, ifAnyGranted = {"ROLE_PROJECT_MANAGER"})
})
@DataTransferObject(javascript = "DefaultConnectionDetails")
public class DefaultConnectionDetails extends AbstractOwnedDomainEntity implements ConnectionDetails {

    private static final long serialVersionUID = 1141611185691118311L;

    @RemoteProperty
    @Column(name = "PORT")
    @GridColumn(order = 3, relativeWidth = 1)
    @FormField(order = 3, type = EntityFilter.WIDGET_TYPE.NUMBER)
    @EntityFilter(order = 3, type = EntityFilter.WIDGET_TYPE.NUMBER)
    private int port = -1;

    @NotEmpty
    @RemoteProperty
    @FormField(order = 2)
    @GridColumn(order = 2)
    @EntityFilter(order = 2)
    @Column(name = "HOSTNAME")
    private String host;

    @NotEmpty
    @RemoteProperty
    @FormField(order = 1)
    @GridColumn(order = 1)
    @EntityFilter(order = 1)
    @Column(name = "PROTOCOL")
    private String protocol;

    @RemoteProperty
    @FormField(order = 4)
    @GridColumn(order = 4)
    @EntityFilter(order = 4)
    @Column(name = "SERVERPATH")
    private String serverPath;

    @Embedded
    @RemoteProperty
    @FormField(order = 5, type = EntityFilter.WIDGET_TYPE.EMBEDDED)
    private UsernamePasswordCredentials credentials;

    @NotEmpty
    @RemoteProperty
    @FormField(order = 5)
    @GridColumn(order = 5)
    @Column(name = "DESCRIPTION")
    private String description;

    @OneToMany(mappedBy = "connectionDetails")
    private Set<DefaultProject> projects;

    /**
     * Accessor method.
     */
    @Override public String getProtocol() {
        return protocol;
    }

    /**
     * Accessor method.
     */
    public void setProtocol(String protocol) {
        this.protocol = protocol != null ? protocol.toLowerCase(Locale.ENGLISH) : null;
    }

    /**
     * Accessor method.
     */
    @Override public String getHost() {
        return host;
    }

    /**
     * Accessor method.
     */
    public void setHost(String host) {
        this.host = host;
    }

    /**
     * Accessor method.
     */
    @Override public int getPort() {
        return port;
    }

    /**
     * Accessor method.
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Accessor method.
     */
    @Override public String getServerPath() {
        return serverPath;
    }

    /**
     * Accessor method.
     */
    public void setServerPath(String serverPath) {
        this.serverPath = serverPath;
    }

    /**
     * Delegates to getUsernamePasswordCredentials()
     */
    @Override public Credentials getCredentials() {
        return getUsernamePasswordCredentials();
    }

    /**
     * Accessor method.
     */
    public final UsernamePasswordCredentials getUsernamePasswordCredentials() {
        return credentials;
    }

    /**
     * Accessor method.
     */
    public void setCredentials(UsernamePasswordCredentials credentials) {
        this.credentials = credentials;
    }

    /**
     * Accessor method.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Accessor method.
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * Accessor method that ensures that the collection is always valid and not modifiable.
     *
     * @return a not empty unmodifiable group of projects
     */
    public Set<DefaultProject> getProjects() {
        return CollectionUtils.isEmpty(projects) ? Collections.EMPTY_SET : Collections.unmodifiableSet(projects);
    }

    /**
     * Accessor method.
     */
    public void setProjects(Set<DefaultProject> projects) {
        if (CollectionUtils.isNotEmpty(this.projects)) {
            this.projects.clear();
        }
        this.projects = projects;
    }

    /**
     * Adds a new Project which connects using this data.
     *
     * @param project anything
     */
    public final void addProject(DefaultProject project) {
        if (project != null) {
            if (projects == null) {
                projects = new HashSet<DefaultProject>();
            }
            projects.add(project);
        }
    }

    /**
     * Delegates to getDescription()
     */
    @Override public final String getCaption(Locale locale) {
        return getDescription();
    }

    /**
     * Delegates to UrlUtils.buildUrl()
     */
    @Override public final String getUrl() {
        return UrlUtils.buildUrl(protocol, host, port, serverPath);
    }

}
